import Vue from 'vue';
import lodash from 'lodash';
import store from '@/store';
const getConstData = async (code) => {
	return await store.dispatch('getConstByCode', code);
}
const getEnumData = async (code) => {
	return await store.dispatch('getEnumByCode', code);
}
const getDictDatas = async (arr, type) => {
	let dicts = Vue.prototype.dictData;
	for (const code of arr) {
		if (dicts && dicts[code]) return false;
		if (type === 'const') {
			let result = await getConstData(code);
			Vue.set(Vue.prototype.dictData, code, result.value);
		} else if (type === 'enum') {
			let result = await getEnumData(code);
			Vue.set(Vue.prototype.dictData, code, result.value);
		}
	}
}
export const dictMixins = {
	async beforeRouteEnter(to, from, next) {
		let toRouter = lodash.last(to.matched);
		let toComponent = toRouter.components?.default;
		if (!!toComponent.consts) {
			await getDictDatas(toComponent.consts, 'const');
		}
		if (!!toComponent.enums) {
			await getDictDatas(toComponent.enums, 'enum');
		}
		next();
	},
	data() {
		return {
			screenWidth: 0
		}
	},
	computed: {
		isMobile() {
			return this.screenWidth < 768;
		},
		isPad() {
			return this.screenWidth < 992 && this.screenWidth >= 768;
		}
	},
	created() {
		this.screenWidth = window.innerWidth;
		window.addEventListener('resize', () => {
			this.screenWidth = window.innerWidth;
		});
		if (!!this.$options.consts) {
			getDictDatas(this.$options.consts, 'const');
		}
		if (!!this.$options.enums) {
			getDictDatas(this.$options.enums, 'enum');
		}
	}
}